package dep_jwt

import (
	"feng-che.com/server/driver-quiz/myApp"
	"github.com/brianvoe/gofakeit/v6"
	"github.com/gofiber/fiber/v2"
	"github.com/golang-jwt/jwt/v5"
	"go.mongodb.org/mongo-driver/bson/primitive"
	"time"
)

// mySigningKey := []byte("AllYourBase")
type MyAppUserClaims struct {
	ID primitive.ObjectID `json:"id,omitempty"`
	jwt.RegisteredClaims
}

// GenerateTokenForClient 生成客户的登录token
func GenerateTokenForUser(id *primitive.ObjectID) (string, error) {
	now := time.Now()
	claims := MyAppUserClaims{
		*id,
		jwt.RegisteredClaims{
			// A usual scenario is to set the expiration time relative to the current time
			ExpiresAt: jwt.NewNumericDate(now.Add(12 * time.Hour)),
			IssuedAt:  jwt.NewNumericDate(now),
			NotBefore: jwt.NewNumericDate(now),
			Issuer:    "wlkj",
			Subject:   "user_login",
			ID:        gofakeit.LetterN(8),
			Audience:  []string{"somebody_else"},
		},
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	ss, err := token.SignedString([]byte(myApp.AppSetting.Jwt.SignKey))
	//fmt.Printf("%v %v", ss, err)
	return ss, err
}

func ParseUserToken(tokenString *string) (*MyAppUserClaims, error) {
	//tokenString := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIiLCJpc3MiOiJ0ZXN0IiwiYXVkIjoic2luZ2xlIn0.QAWg1vGvnqRuCFTMcPkjZljXHh8U3L_qUjszOtQbeaA"
	token, err := jwt.ParseWithClaims(*tokenString, &MyAppUserClaims{}, func(token *jwt.Token) (interface{}, error) {
		return []byte(myApp.AppSetting.Jwt.SignKey), nil
	})
	if err != nil {
		return nil, err
	}
	if claims, ok := token.Claims.(*MyAppUserClaims); ok && token.Valid {
		return claims, nil
	} else {
		return claims, err
	}
}

// VerifyClientForNext 解析client的token，并写入下一步
func VerifyUserForNext(c *fiber.Ctx) error {
	authorizationString := c.Get("Authorization")
	if authorizationString == "" {
		return fiber.NewError(600, "没有携带登录信息")
	}
	UserClaims, err := ParseUserToken(&authorizationString)
	if err != nil {
		return fiber.NewError(600, "登录信息错误,请尝试重新登录."+err.Error())
	}
	c.Locals("UserID", &UserClaims.ID)
	return c.Next()
}
